<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">

  <el-row :gutter="10">

      <el-col :span="8">
      <el-form-item label="账单编号" prop="billNo">
        <el-input
          v-model="queryParams.billNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 350px;"
        />
      </el-form-item></el-col>




       <el-col :span="8">
      <el-form-item label="老人姓名" style="width: 400px;" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item></el-col>
       <el-col :span="8">
      <el-form-item label="老人身份证号" style="width: 400px;" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />


        
      </el-form-item></el-col>
<br/>
      <el-form-item style="margin-left: 50px;">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="Timer" @click="handleTestGenerateBills" :loading="testLoading">
          测试生成下月账单
        </el-button>
      </el-form-item>

     </el-row> 
     <hr/>
    </el-form>



    

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:bill:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bill:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bill:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:bill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->
<!-- 账单状态筛选 -->

 <el-button-group class="ml-4">
  <el-button    color="white"   type="info" @click="quanbu">全部</el-button>
    <el-button  color="white"   type="info" @click="daizhifu">待支付</el-button>
    <el-button  color="white"  type="info" @click="yizhi">已支付</el-button>
    <el-button  color="white" type="info" @click="yiguanbi">已关闭</el-button>
  </el-button-group>

<button class="apply1"  style="float: right;" type="primary" @click="openGenerateDialog">生成月度账单</button>





    <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55px" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="账单编号" align="center" prop="billNo" />
      <el-table-column label="账单类型" align="center" prop="billType" />
      <el-table-column label="账单月份" align="center" prop="billMonth" />
      <!-- <el-table-column label="老人外键" align="center" prop="elderlyId" /> -->
 <el-table-column label="老人姓名" align="center" prop="elderly.name" />
      <el-table-column label="老人身份证号" align="center" prop="elderly.idCard" />
      <el-table-column label="账单金额" align="center" prop="billAmount" />
      <el-table-column label="应付金额" align="center" prop="payableAmount" />
      <el-table-column label="支付截至日期" align="center" prop="paymentDeadline" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDeadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

       <el-table-column label="交易状态" align="center" prop="transactionStatus">
        <template #default="scope">
          <dict-tag :options="lekang_orderstatus" :value="scope.row.transactionStatus"/>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
   
    
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:bill:edit']">修改</el-button> -->
          <el-button link type="primary" 
                     :disabled="scope.row.transactionStatus === '已支付' || scope.row.transactionStatus === '已关闭'"
                     @click="handlePay(scope.row)" 
                     v-hasPermi="['system:bill:remove']">支付</el-button>
          <el-button link type="primary" 
                     :disabled="scope.row.transactionStatus === '已支付' || scope.row.transactionStatus === '已关闭'"
                     @click="handleCancelBill(scope.row)" 
                     v-hasPermi="['system:bill:remove']">取消</el-button>
          <el-button link type="primary" 
                     @click="handleView(scope.row)" 
                     v-hasPermi="['system:bill:list']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入账列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="billRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账单编号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入账单编号" />
        </el-form-item>
        <el-form-item label="账单月份" prop="billMonth">
          <el-input v-model="form.billMonth" placeholder="请输入账单月份" />
        </el-form-item>
        <el-form-item label="老人外键" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键" />
        </el-form-item>
        <el-form-item label="每月应付" prop="monthlyPayable">
          <el-input v-model="form.monthlyPayable" placeholder="请输入每月应付" />
        </el-form-item>
        <el-form-item label="本期应付" prop="currentPayable">
          <el-input v-model="form.currentPayable" placeholder="请输入本期应付" />
        </el-form-item>
        <el-form-item label="预交款支付金额" prop="prepaymentAmount">
          <el-input v-model="form.prepaymentAmount" placeholder="请输入预交款支付金额" />
        </el-form-item>
        <el-form-item label="账单金额" prop="billAmount">
          <el-input v-model="form.billAmount" placeholder="请输入账单金额" />
        </el-form-item>
        <el-form-item label="应付金额" prop="payableAmount">
          <el-input v-model="form.payableAmount" placeholder="请输入应付金额" />
        </el-form-item>
        <el-form-item label="支付截至日期" prop="paymentDeadline">
          <el-date-picker clearable
            v-model="form.paymentDeadline"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付截至日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易状态" prop="transactionStatus">
          <el-radio-group v-model="form.transactionStatus">
            <el-radio
              v-for="dict in lekang_orderstatus"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账单开始时间" prop="billStartTime">
          <el-date-picker clearable
            v-model="form.billStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择账单开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账单结束时间" prop="billEndTime">
          <el-date-picker clearable
            v-model="form.billEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择账单结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="支付渠道" prop="paymentChannel">
          <el-input v-model="form.paymentChannel" placeholder="请输入支付渠道" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="支付凭证图片" prop="paymentVoucher">
          <el-input v-model="form.paymentVoucher" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="支付备注" prop="paymentRemark">
          <el-input v-model="form.paymentRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input v-model="form.cancelReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="关联订单" prop="relatedOrder">
          <el-input v-model="form.relatedOrder" placeholder="请输入关联订单" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 生成月度账单弹窗 -->
  <el-dialog v-model="generateDialogVisible" title="生成月度账单" width="520px" append-to-body>
    <el-form ref="generateRef" :model="generateForm" :rules="generateRules" label-width="100px">
      <el-form-item label="老人姓名" prop="elderlyId">
        <el-input v-model="generateForm.elderlyName" placeholder="请选择" readonly @click="openSelectElderDialog" style="width: 360px;" />
      </el-form-item>
      <el-form-item label="账单月份" prop="billMonth">
        <el-date-picker
          v-model="generateForm.billMonth"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择账单月份"
          :disabled-date="disableCurrentAndFutureMonth"
          style="width: 360px;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGenerate">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择老人弹窗 -->
  <el-dialog v-model="selectElderVisible" title="选择老人" width="720px" append-to-body>
    <el-input v-model="elderSearch" placeholder="按姓名搜索" clearable style="width: 240px; margin-bottom: 10px;" @input="fetchElders" />
    <el-table :data="elderList" height="360">
      <el-table-column width="60" label="选择" align="center">
        <template #default="{ row }">
          <el-radio v-model="selectedElderId" :label="row.id" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="idCard" label="身份证号" align="center" />
      <el-table-column prop="checkInStatus" label="入住状态" align="center" />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="selectElderVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectElder">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 上传支付凭证弹窗 -->
  <el-dialog v-model="paymentDialogVisible" title="上传支付凭证" width="500px" :before-close="handlePaymentCancel" class="payment-dialog">
    <el-form ref="paymentFormRef" :model="paymentForm" :rules="paymentRules" label-width="100px">
      <el-form-item label="支付方式" prop="paymentMethod" required>
        <el-select v-model="paymentForm.paymentMethod" placeholder="请选择" style="width: 100%;">
          <el-option label="微信支付" value="wechat"></el-option>
          <el-option label="支付宝" value="alipay"></el-option>
          <el-option label="银行卡" value="bank"></el-option>
          <el-option label="现金" value="cash"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付凭证">
        <el-upload
          class="payment-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :on-error="handleUploadError"
          :headers="uploadHeaders"
        >
          <img 
            v-if="paymentProofList.length > 0" 
            :src="getImageDisplayUrl(paymentProofList[0])" 
            class="payment-image" 
            @error="handleImageError"
            @load="handleImageLoad"
          />
          <el-icon v-else class="payment-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-hint">
          <div>图片大小不超过2M</div>
          <div>仅支持上传PNG、JPG、JPEG类型图片</div>
          <div v-if="paymentProofList.length > 0" class="selected-image-info">
            <div class="image-name" :title="paymentProofList[0].name">
              已选择图片: {{ truncateFileName(paymentProofList[0].name) }}
            </div>
            <div class="debug-info" style="margin-top: 4px; font-size: 10px; color: #999;">
              调试URL: {{ getImageDisplayUrl(paymentProofList[0]) }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="支付备注" prop="paymentRemark" required>
        <el-input
          v-model="paymentForm.paymentRemark"
          type="textarea"
          placeholder="请输入"
          maxlength="50"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlePaymentCancel">取消</el-button>
        <el-button type="primary" @click="handlePaymentConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="Bill">
import { listBill, getBill, delBill, addBill, updateBill, generateBill, triggerGenerateMonthlyBills } from "@/api/system/bill"
import request from "@/utils/request"
import { listElderly } from "@/api/system/elderly"
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Plus } from '@element-plus/icons-vue'
import { listBalance } from '@/api/system/balance'

const { proxy } = getCurrentInstance()
const { lekang_orderstatus } = proxy.useDict('lekang_orderstatus')

const billList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 支付弹窗相关
const paymentDialogVisible = ref(false)
const currentBillId = ref(null)
// 保存当前操作的账单行，以便带上elderlyId和payableAmount
const currentBillRow = ref(null)
const paymentForm = ref({
  paymentMethod: '',
  paymentRemark: ''
})
const paymentRules = ref({
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  paymentRemark: [
    { required: true, message: '请输入支付备注', trigger: 'blur' },
    { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
  ]
})

// 测试生成账单相关
const testLoading = ref(false)
const paymentProofList = ref([])
const paymentFormRef = ref(null)
const fileInput = ref(null)
const uploadUrl = ref('/dev-api/common/upload')
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + getToken()
})

// 如果后端接口有问题，可以临时使用这个测试接口
// const uploadUrl = ref('https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    billNo: null,
    elderlyId: null,
      transactionStatus: null, // 新增：交易状态筛选参数
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 生成月度账单：状态
const generateDialogVisible = ref(false)
const generateForm = ref({ elderlyId: null, elderlyName: '', billMonth: '' })
const generateRef = ref(null)
const generateRules = ref({
  elderlyId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  billMonth: [{ required: true, message: '请选择账单月份', trigger: 'change' }]
})

// 选择老人
const selectElderVisible = ref(false)
const elderList = ref([])
const elderSearch = ref('')
const selectedElderId = ref(null)

/** 查询入账列表列表 */
function getList() {
  loading.value = true
  listBill(queryParams.value).then(response => {
    billList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log(response);
    
  })
}




// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    billNo: null,
    billType: null,
    billMonth: null,
    elderlyId: null,
    monthlyPayable: null,
    currentPayable: null,
    prepaymentAmount: null,
    billAmount: null,
    payableAmount: null,
    paymentDeadline: null,
     transactionStatus: null, // 新增：交易状态筛选参数
    billStartTime: null,
    billEndTime: null,
    creator: null,
    createTime: null,
    paymentChannel: null,
    paymentMethod: null,
    paymentVoucher: null,
    paymentRemark: null,
    cancelReason: null,
    relatedOrder: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("billRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // getList()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加入账列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBill(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改入账列表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["billRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBill(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBill(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除入账列表编号为"' + _ids + '"的数据项？').then(function() {
    return delBill(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})}

/** 支付按钮操作 */
function handlePay(row) {
  // 检查状态是否为待支付
  if (row.transactionStatus !== '待支付') {
    proxy.$modal.msgWarning('只有待支付的账单才能进行支付操作')
    return
  }
  
  // 重置支付表单
  resetPaymentForm()
  // 设置当前操作的账单ID
  currentBillId.value = row.id
  currentBillRow.value = row
  console.log('开始支付操作，账单ID:', row.id);
  // 显示支付弹窗
  paymentDialogVisible.value = true
}

/** 重置支付表单 */
function resetPaymentForm() {
  paymentForm.value = {
    paymentMethod: '',
    paymentRemark: ''
  }
  paymentProofList.value = []
  if (paymentFormRef.value) {
    paymentFormRef.value.resetFields()
  }
}

/** 关闭支付弹窗 */
function handlePaymentCancel() {
  resetPaymentForm()
  paymentDialogVisible.value = false
}

/** 确认支付 */
function handlePaymentConfirm() {
  // 先检查文件是否上传
  if (paymentProofList.value.length === 0) {
    proxy.$modal.msgWarning('请上传支付凭证')
    return
  }
  
  // 确保账单ID存在
  if (!currentBillId.value) {
    console.error('错误: 账单ID不存在');
    proxy.$modal.msgError('支付失败，账单信息异常')
    return
  }
  
  paymentFormRef.value.validate((valid) => {
    if (valid) {
      
      // 确保表单数据已正确绑定
      console.log('表单数据:', paymentForm.value);
      console.log('支付凭证列表:', paymentProofList.value);
      console.log('当前账单ID:', currentBillId.value);
      
      // 再次确保支付方式和支付备注不为空
      if (!paymentForm.value.paymentMethod) {
        console.error('错误: 支付方式不能为空');
        proxy.$modal.msgError('请选择支付方式')
        return
      }
      
      if (!paymentForm.value.paymentRemark) {
        console.error('错误: 支付备注不能为空');
        proxy.$modal.msgError('请输入支付备注')
        return
      }
      
      // 创建支付请求数据
      const payData = {
        id: currentBillId.value,
        transactionStatus: '已支付',
        paymentTime: new Date().toISOString().split('T')[0], // 设置支付日期为今天
        paymentChannel: 'system',
        paymentMethod: paymentForm.value.paymentMethod || '',
        paymentRemark: paymentForm.value.paymentRemark || '',
        // 只保存文件名，不保存完整路径
        paymentVoucher: paymentProofList.value[0] && paymentProofList.value[0].name 
          ? paymentProofList.value[0].name 
      : '',
    // 关键字段：让后端能扣减余额
    elderlyId: currentBillRow.value?.elderlyId || null,
    payableAmount: currentBillRow.value?.payableAmount || null
      }
      
      console.log('提交的支付数据(JSON处理后):', payData);
      console.log('支付方式字段是否存在:', 'payment_method' in payData);
      console.log('支付方式值:', payData.payment_method);
      console.log('支付备注字段是否存在:', 'payment_remark' in payData);
      console.log('支付备注值:', payData.payment_remark);
      console.log('支付凭证字段是否存在:', 'payment_proof' in payData);
      console.log('支付凭证值长度:', payData.payment_proof ? payData.payment_proof.length : 0);
      
      // 直接使用request工具函数调用更新接口，确保数据正确传递
      console.log('使用直接请求方式');
      request({
        url: '/system/bill',
        method: 'put',
        data: payData,
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then(response => {
        console.log('直接请求支付接口响应:', response);
        
        if (response && response.code === 200) {
          proxy.$modal.msgSuccess('支付成功')
          // 关闭弹窗
          paymentDialogVisible.value = false
          // 刷新列表数据
          getList()
          // 支付成功后，尝试通知余额页面刷新（如果在同标签页打开过余额页）
          tryRefreshBalancePage()
          // 同时直接拉取该老人的最新余额单条数据并推送到余额页
          tryPushSingleBalance()
        } else {
          proxy.$modal.msgError('支付失败，返回状态异常')
          console.error('直接请求支付返回状态异常:', response);
        }
      }).catch(error => {
        console.error('直接请求支付失败详情:', error);
        console.error('错误堆栈:', error.stack);
        proxy.$modal.msgError('支付失败，请重试')
      })
    } else {
      console.log('表单验证失败');
      // 显示验证失败的字段
      const fields = paymentFormRef.value.fields;
      fields.forEach(field => {
        if (field.validateState === 'error') {
          console.log('验证失败的字段:', field.prop, '错误信息:', field.errors);
        }
      });
    }
  })
}

/** 支付成功后刷新预交款余额页面（若已打开） */
function tryRefreshBalancePage() {
  const elderId = currentBillRow.value?.elderlyId
  if (!elderId) return
  // 通过事件通道通知其它页面（余额页）刷新
  try {
    window.dispatchEvent(new CustomEvent('balance:refresh', { detail: { elderlyId: elderId } }))
  } catch (e) {}
}

/** 拉取单个余额并推送给余额页，仅更新该老人一条记录 */
function tryPushSingleBalance() {
  const elderId = currentBillRow.value?.elderlyId
  if (!elderId) return
  listBalance({ pageNum: 1, pageSize: 1, elderlyId: elderId }).then(res => {
    const row = Array.isArray(res?.rows) ? res.rows[0] : null
    if (row) {
      try {
        window.dispatchEvent(new CustomEvent('balance:updateOne', { detail: { elderlyId: elderId, row } }))
      } catch (e) {}
    }
  }).catch(() => {})
}

/** 处理文件上传超过数量限制 */
function handleExceed(files, fileList) {
  proxy.$modal.msgWarning(`只能上传一个文件`)
}


/** 删除上传的图片 */
function handleRemove() {
  paymentProofList.value = []
}

/** 图片加载成功 */
function handleImageLoad() {
  console.log('图片加载成功')
  console.log('当前图片URL:', getImageDisplayUrl(paymentProofList.value[0]))
}

/** 图片加载失败 */
function handleImageError(event) {
  console.error('图片加载失败:', event)
  console.error('尝试加载的图片URL:', event.target.src)
  console.error('图片信息:', paymentProofList.value[0])
  
  // 如果服务器图片加载失败，尝试其他路径
  if (paymentProofList.value.length > 0 && !paymentProofList.value[0].isLocal) {
    console.log('尝试其他图片路径...')
    tryAlternativeImageUrl(event.target)
  } else {
    proxy.$modal.msgWarning('图片加载失败，请重新上传')
  }
}

/** 尝试其他图片路径 */
function tryAlternativeImageUrl(imgElement) {
  const imageInfo = paymentProofList.value[0]
  if (!imageInfo) return
  
  const baseUrl = import.meta.env.VITE_APP_BASE_API || '/dev-api'
  const fileName = imageInfo.name || imageInfo.url.split('/').pop()
  
  // 尝试不同的路径
  const alternativeUrls = [
    `${baseUrl}/profile/upload/${fileName}`,
    `${baseUrl}/common/download/${fileName}`,
    `${baseUrl}/files/${fileName}`,
    `${baseUrl}/upload/${fileName}`
  ]
  
  let currentIndex = 0
  
  const tryNextUrl = () => {
    if (currentIndex >= alternativeUrls.length) {
      console.error('所有图片路径都尝试失败')
      proxy.$modal.msgWarning('图片加载失败，请重新上传')
      return
    }
    
    const testUrl = alternativeUrls[currentIndex]
    console.log(`尝试路径 ${currentIndex + 1}/${alternativeUrls.length}:`, testUrl)
    
    // 创建新的图片对象测试
    const testImg = new Image()
    testImg.onload = () => {
      console.log('找到可用路径:', testUrl)
      imgElement.src = testUrl
      proxy.$modal.msgSuccess('图片加载成功')
    }
    testImg.onerror = () => {
      currentIndex++
      tryNextUrl()
    }
    testImg.src = testUrl
  }
  
  tryNextUrl()
}

/** 截断文件名显示 */
function truncateFileName(fileName, maxLength = 30) {
  if (!fileName) return ''
  if (fileName.length <= maxLength) return fileName
  
  // 获取文件扩展名
  const lastDotIndex = fileName.lastIndexOf('.')
  if (lastDotIndex === -1) {
    // 没有扩展名，直接截断
    return fileName.substring(0, maxLength - 3) + '...'
  }
  
  const nameWithoutExt = fileName.substring(0, lastDotIndex)
  const extension = fileName.substring(lastDotIndex)
  
  // 保留扩展名，截断文件名部分
  const maxNameLength = maxLength - extension.length - 3 // 3 for '...'
  if (nameWithoutExt.length <= maxNameLength) {
    return fileName
  }
  
  return nameWithoutExt.substring(0, maxNameLength) + '...' + extension
}

/** 获取图片显示URL */
function getImageDisplayUrl(imageInfo) {
  if (!imageInfo) return ''
  
  // 如果是本地预览（FileReader生成的base64）
  if (imageInfo.isLocal) {
    console.log('使用本地预览URL:', imageInfo.url)
    return imageInfo.url
  }
  
  // 如果是服务器图片，构建正确的访问URL
  const baseUrl = import.meta.env.VITE_APP_BASE_API || '/dev-api'
  const url = imageInfo.url || ''
  // 1) 完整URL，直接返回
  if (/^https?:\/\//i.test(url)) return url
  // 2) 以 /profile 或 /common 开头，拼接网关前缀
  if (url.startsWith('/')) return baseUrl + url
  // 3) 仅文件名，按若依默认规则拼接
  return `${baseUrl}/profile/upload/${url}`
}

/** 上传成功回调 */
function handleUploadSuccess(response, file) {
  proxy.$modal.closeLoading()
  console.log('上传响应:', response)
  console.log('文件信息:', file)
  
  if (response && response.code === 200) {
    // RuoYi 返回 { url: '/profile/upload/xxx.jpg', fileName: 'xxx.jpg' }
    const baseUrl = import.meta.env.VITE_APP_BASE_API || '/dev-api'
    const serverUrl = response.url ? (/^https?:\/\//i.test(response.url) ? response.url : (baseUrl + response.url)) : ''
    const fileName = (response.fileName || file?.name || '').split('/').pop()

    paymentProofList.value = [{ name: fileName, url: serverUrl || fileName, isLocal: false }]
    console.log('图片访问URL:', serverUrl)
    proxy.$modal.msgSuccess('图片上传成功')
  } else {
    console.error('上传失败，响应:', response)
    proxy.$modal.msgError(response?.msg || '图片上传失败')
  }
}

/** 上传前校验 */
function beforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    proxy.$modal.msgWarning('上传图片大小不能超过 2MB!')
    return false
  }
  
  const isImage = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg'
  if (!isImage) {
    proxy.$modal.msgWarning('仅支持上传PNG、JPG、JPEG类型图片!')
    return false
  }
  
  // 创建本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    paymentProofList.value = [{
      name: file.name,
      url: e.target.result,
      isLocal: true
    }]
  }
  reader.readAsDataURL(file)
  
  proxy.$modal.loading('正在上传图片，请稍候...')
  return true
}

/** 上传失败回调 */
function handleUploadError(error, file, fileList) {
  proxy.$modal.closeLoading()
  console.error('图片上传失败:', error)
  console.error('文件信息:', file)
  console.error('文件列表:', fileList)
  
  let errorMessage = '图片上传失败，请重试'
  if (error && error.message) {
    errorMessage = error.message
  } else if (error && error.response) {
    errorMessage = error.response.data?.msg || error.response.statusText || '服务器错误'
  }
  
  proxy.$modal.msgError(errorMessage)
}

/** 取消账单操作 */
function handleCancelBill(row) {
  // 检查状态是否为待支付
  if (row.transactionStatus !== '待支付') {
    proxy.$modal.msgWarning('只有待支付的账单才能进行取消操作')
    return
  }
  
  proxy.$modal.prompt('请输入取消原因', '取消账单').then(({ value }) => {
    // 创建取消请求数据
    const cancelData = {
      id: row.id,
      transactionStatus: '已关闭',
      cancelReason: value || '用户取消'
    }
    
    // 调用更新接口
    updateBill(cancelData).then(response => {
      proxy.$modal.msgSuccess('账单已取消')
      // 刷新列表数据
      getList()
    }).catch(error => {
      proxy.$modal.msgError('取消失败，请重试')
      console.error('取消失败:', error)
    })
  }).catch(() => {})}

import { useRouter } from 'vue-router'

const router = useRouter()

/** 查看按钮操作 - 跳转到详情页面 */
function handleView(row) {
  // 跳转到详情页面
  router.push({
    path: '/system/bill/detail',
    query: { id: row.id }
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/bill/export', {
    ...queryParams.value
  }, `bill_${new Date().getTime()}.xlsx`)
}

getList()


//状态筛选
function quanbu() {
   queryParams.value.transactionStatus =null
resetQuery()
  // getList()
}
//待支付
function daizhifu() {
 
  queryParams.value.transactionStatus ="待支付"
  //  billList.value = response.rows
  console.log(queryParams.value);
  getList()
}
//已支付
function yizhi() {
  
  queryParams.value.transactionStatus ="已支付"
  getList()
}
//已关闭
function yiguanbi() {

  queryParams.value.transactionStatus ="已关闭"
  getList()
}

// 打开生成月度账单对话框
function openGenerateDialog() {
  // 默认账单月份为下一个月
  const now = new Date()
  const next = new Date(now.getFullYear(), now.getMonth() + 1, 1)
  // 默认选择为下一个月
  generateForm.value.billMonth = `${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, '0')}`
  generateForm.value.elderlyId = null
  generateForm.value.elderlyName = ''
  generateDialogVisible.value = true
}

// 仅允许选择当前月份之后的月份（不包含本月）
function disableCurrentAndFutureMonth(date) {
  const today = new Date()
  // 阈值：下个月的第一天；小于该日期的月份全部禁用
  const nextMonthStart = new Date(today.getFullYear(), today.getMonth() + 1, 1)
  return date < nextMonthStart
}

// 打开选择老人对话框
function openSelectElderDialog() {
  selectElderVisible.value = true
  fetchElders()
}

// 拉取已入住且未退住老人
function fetchElders() {
  listElderly({ status: '已入住', leaveStatus: '未退住', name: elderSearch.value }).then(res => {
    elderList.value = res.rows || []
  })
}

// 选中老人
function confirmSelectElder() {
  const elder = elderList.value.find(e => e.id === selectedElderId.value)
  if (!elder) {
    proxy.$modal.msgWarning('请选择老人')
    return
  }
  generateForm.value.elderlyId = elder.id
  generateForm.value.elderlyName = elder.name
  selectElderVisible.value = false
}

// 提交生成
function submitGenerate() {
  generateRef.value.validate(valid => {
    if (!valid) return
    const elderlyId = generateForm.value.elderlyId
    const billMonth = generateForm.value.billMonth
    
    // 调用专用的生成账单接口
    generateBill({ elderlyId, billMonth }).then((resp) => {
      if (resp && resp.code === 200) {
        proxy.$modal.msgSuccess('月度账单生成成功')
        generateDialogVisible.value = false
        getList()
      } else {
        proxy.$modal.msgError(resp?.msg || '账单生成失败')
      }
    }).catch((err) => {
      console.error('生成账单失败:', err)
      proxy.$modal.msgError(err?.msg || '账单生成失败，请重试')
    })
  })
}

// 测试生成下月账单
function handleTestGenerateBills() {
  proxy.$modal.confirm('确认要测试生成所有老人下月账单吗？\n这将调用定时器功能为所有已入住老人生成下月账单。').then(() => {
    testLoading.value = true
    
    // 调用后端API触发定时器生成账单
    triggerGenerateMonthlyBills().then(response => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess('测试生成成功！已为所有老人生成下月账单。')
        // 刷新列表
        getList()
      } else {
        proxy.$modal.msgError('测试生成失败：' + (response.msg || '未知错误'))
      }
    }).catch(error => {
      console.error('测试生成账单失败:', error)
      proxy.$modal.msgError('测试生成失败：' + (error.message || '网络错误'))
    }).finally(() => {
      testLoading.value = false
    })
  }).catch(() => {
    // 用户取消操作
  })
}





</script>


<style scoped>
.ml-4 {
  margin-left: 16px;
  margin-top: 30px;
   margin-bottom: 20px;
   border-style: solid;
   border-width: 1px;
   border-color: #e4e7ed;
}

.apply1{
  /* margin-left: 1500px; */
  width: 130px;
  height: 28px;
  background-color: #0000FF;
  color: white;
  border-style: none;
border-radius: 5px;
margin-top: 20px;
}

/* 支付弹窗样式 */
.payment-dialog :deep(.el-dialog__body) {
  padding: 20px 20px 10px 20px;
}

.payment-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

.payment-dialog :deep(.el-form-item__label::before) {
  color: #f56c6c;
  margin-right: 4px;
}

/* 支付凭证上传样式 */
.payment-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.payment-uploader .payment-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.payment-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.selected-image-info {
  margin-top: 8px;
}

.image-name {
  font-size: 12px;
  color: #67c23a;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  display: block;
}

/* 弹窗底部按钮样式 */
.payment-dialog :deep(.dialog-footer) {
  text-align: right;
  padding: 10px 0 0 0;
}

.payment-dialog :deep(.dialog-footer .el-button) {
  margin-left: 10px;
}

/* 表单样式优化 */
.payment-dialog :deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

.payment-dialog :deep(.el-input__count) {
  color: #909399;
  font-size: 12px;
}
</style>